<script setup lang="tsx">
import { computed, ref } from 'vue';
import type { TreeNodeData } from 'element-plus';
import { ElButton, ElPopconfirm, ElTag } from 'element-plus';
import {
  fetchDeleteDeptInfoBatchByIds,
  fetchDeleteDeptInfoById,
  fetchGetDeptInfoByPage,
  fetchGetDeptTraceTextById
} from '@/service/api';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useRouterPush } from '@/hooks/common/router';
import { $t } from '@/locales';
import DeptFormDrawer from '@/views/system/dept/modules/dept-form-drawer.vue';
import DeptSearch from '@/views/system/dept/modules/dept-search.vue';
import DeptTree from '@/views/system/dept/modules/dept-tree.vue';

defineOptions({ name: 'DeptManage' });

// 页面导航
const { routerPushByKey } = useRouterPush();

const { routerPush } = useRouterPush();

const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetDeptInfoByPage,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    condition: {}
  },
  columns: () => [
    { type: 'selection', width: 48 },
    { prop: 'index', label: $t('common.index'), width: 64 },
    { prop: 'name', label: '部门名称', minWidth: 200, align: 'left' },
    { prop: 'code', label: '部门编码', minWidth: 200, align: 'left' },
    { prop: 'shortName', label: '部门简称', minWidth: 200, align: 'left' },
    {
      prop: 'typeText',
      label: '部门类型',
      minWidth: 125,
      align: 'center',
      formatter: row => <ElTag>{row.typeText}</ElTag>
    },
    {
      prop: 'enabled',
      label: $t('form.enabled'),
      width: 100,
      align: 'center',
      formatter: row => (
        <ElTag type={row.enabled === 1 ? 'success' : 'danger'}>
          {row.enabled === 1 ? $t('form.enabledOptions.enabled') : $t('form.enabledOptions.disabled')}
        </ElTag>
      )
    },
    { prop: 'orderNum', label: $t('form.orderNum'), width: 100 },
    {
      prop: 'operate',
      label: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      width: 200,
      formatter: row => (
        <div class="flex-center">
          <ElButton type="info" plain size="small" onClick={() => deptAuthorization(row)}>
            {$t('common.authorization')}
          </ElButton>
          <ElButton type="primary" plain size="small" onClick={() => edit(row.id)}>
            {$t('common.edit')}
          </ElButton>
          <ElPopconfirm title={$t('common.confirmDelete')} onConfirm={() => handleDelete(row.id)}>
            {{
              reference: () => (
                <ElButton type="danger" plain size="small">
                  {$t('common.delete')}
                </ElButton>
              )
            }}
          </ElPopconfirm>
        </div>
      )
    }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // closeDrawer,
} = useTableOperate(data, getData);

const refreshTree = ref<number>(0);

async function handleBatchDelete() {
  // ids
  const ids: Array<CommonType.IdType> = checkedRowKeys.value.map(item => item.id);
  // request
  const { error } = await fetchDeleteDeptInfoBatchByIds(ids);
  if (error) return;
  await onBatchDeleted();
  refreshTree.value += 1;
}

async function handleDelete(id: CommonType.IdType) {
  try {
    // request
    const { error } = await fetchDeleteDeptInfoById(id);
    // success
    if (error) return;
    await onDeleted();
    refreshTree.value += 1;
  } catch {
    //
  }
}

/** 编辑部门 */
function edit(id: CommonType.IdType) {
  handleEdit(id);
}

/** 当前选中的部门节点，新增时作为上级部门 */
const currentNode = ref<TreeNodeData | null>(null);

// 当前上级部门
const currentDeptText = ref<string>('');

async function handleGetDeptTraceTextById() {
  const deptId = Number(currentNode.value?.value || '0');
  if (deptId > 0) {
    const { data: text, error } = await fetchGetDeptTraceTextById(deptId);
    if (error) return;
    currentDeptText.value = text;
  }
}

/** 处理部门节点点击事件 */
function nodeClick(node: TreeNodeData) {
  currentNode.value = node || null;
  searchParams.condition!.parentId = node.value || 0;
  handleGetDeptTraceTextById();
  getDataByPage();
}

/** 当页最大的 orderNum */
const maxOrderNum = computed(() => {
  if (data.value && data.value.length > 0) {
    return data.value[data.value.length - 1].orderNum;
  }
  return 0;
});

function formSubmitted() {
  getDataByPage();
  refreshTree.value += 1;
}

// 部门授权
function deptAuthorization(row: Api.System.Dept.DeptInfoRecord) {
  routerPushByKey('system_dept-role', {
    query: {
      deptId: row.id as string
    }
  });
}
</script>

<template>
  <ElSplitter>
    <ElSplitterPanel collapsible class="mr2" :size="250">
      <ElCard class="h-full card-wrapper">
        <DeptTree :refresh="refreshTree" @node-click="nodeClick" />
      </ElCard>
    </ElSplitterPanel>
    <ElSplitterPanel class="ml2 w-full">
      <ElContainer>
        <ElHeader>
          <ElCard class="card-wrapper" :body-style="{ paddingTop: 0, paddingBottom: 0 }">
            <DeptSearch v-model="searchParams.condition" @reset="resetSearchParams" @search="getDataByPage" />
          </ElCard>
        </ElHeader>
        <ElHeader v-if="!!currentDeptText">
          <ElAlert type="info" :closable="false">上级部门：{{ currentDeptText }}</ElAlert>
        </ElHeader>
        <ElMain>
          <ElCard class="h-full sm:flex-1-hidden card-wrapper">
            <template #header>
              <div class="flex flex-wrap items-center justify-between gap-5">
                <p>部门列表</p>
                <TableHeaderOperation
                  v-model:columns="columnChecks"
                  :disabled-delete="checkedRowKeys.length === 0"
                  :loading="loading"
                  @add="handleAdd"
                  @refresh="getData"
                  @delete="handleBatchDelete"
                >
                  <template #prefix>
                    <ElButton type="primary" plain @click="routerPush({ name: 'system_dept-type' })">
                      配置部门类型
                    </ElButton>
                  </template>
                </TableHeaderOperation>
              </div>
            </template>
            <div class="h-[calc(100%-45px)]">
              <ElTable
                v-loading="loading"
                height="100%"
                border
                class="sm:h-full"
                :data="data"
                row-key="id"
                show-overflow-tooltip
                @selection-change="checkedRowKeys = $event"
              >
                <ElTableColumn v-for="col in columns" :key="col.prop" v-bind="col" />
              </ElTable>
            </div>
            <div class="mt15px flex justify-end">
              <ElPagination
                v-if="mobilePagination.total"
                background
                layout="total,prev,pager,next,sizes"
                v-bind="mobilePagination"
                @current-change="mobilePagination['current-change']"
                @size-change="mobilePagination['size-change']"
              />
            </div>
          </ElCard>
          <DeptFormDrawer
            v-model:visible="drawerVisible"
            :operate-type="operateType"
            :row-data="editingData"
            :parent-id="currentNode?.value"
            :max-order-num="maxOrderNum"
            @submitted="formSubmitted"
          />
        </ElMain>
      </ElContainer>
    </ElSplitterPanel>
  </ElSplitter>
</template>

<style scoped>
.el-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;

  .el-header {
    padding: 0;
    height: auto;
  }

  .el-main {
    padding: 0;
    height: 0;
    flex: 1;
  }
}

:deep(.el-card) {
  display: flex;
  flex-direction: column;
}

:deep(.el-card .el-card__body) {
  flex: 1;
  height: 0;
}

:deep(.el-table .cell) {
  padding: 0 10px;
}
</style>
